package com.lrs.java.jdbc.jdbc_exercise;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * 在java中展现数据库表中的树状结构。其中tree方法使用一个参数。
 * @author Administrator
 *
 */
public class Tree_Ariticle_2 {
	static Connection conn = null;
	
	
	public static void tree(int id) {
		String sql = "select * from article where pid = " + id;
//		for(int i=0; i<grade; i++) {
//			preStr += "****";
//		}
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			rs = stmt.executeQuery(sql);
			
			while(rs.next()) {
				String preStr = "";
				for(int i=0; i<rs.getInt("alevel"); i++) {
					preStr += "****";
				}
				System.out.println(preStr + rs.getString("cont"));
				if(rs.getInt("isleaf") == 0) {
					tree(rs.getInt("id"));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(rs != null) {
					rs.close();
					rs = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
			try {
				if(stmt != null) {
					stmt.close();
					stmt = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}	
		
	}
	public static void main(String[] args) {		
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ZLPD", "scott", "tiger");
			tree(0);
			
			System.out.println("success!");
			
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if(conn != null) {
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
}
